package com.yc.commontlib.base

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.annotation.MainThread
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.*
import androidx.viewbinding.ViewBinding
import com.yc.commontlib.extension.YcViewBindingProperty
import kotlinx.coroutines.launch

/**
 * Creator: yc
 * Date: 2021/6/9 16:47
 * UseDes:
 */
@SuppressLint("SetTextI18n")
abstract class YcBaseActivity<V : ViewBinding>(private val createVB: ((LayoutInflater) -> V)? = null) : AppCompatActivity() {
    lateinit var mViewBinding: V
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (createVB != null) {
            mViewBinding = createVB.invoke(LayoutInflater.from(this as Context))
            setContentView(mViewBinding.root)
        }
        initView()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    abstract fun initView()
    @MainThread
    public inline fun <reified VM : ViewModel> ComponentActivity.ycViewModels(
        noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
    ): Lazy<VM> {
        val factoryPromise = factoryProducer ?: {
            defaultViewModelProviderFactory
        }
        return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)
    }

    protected fun launch(block: suspend () -> Unit) =
        lifecycleScope.launch {
            block()
        }

    protected fun <T> LiveData<T>.observe(observer: Observer<T>) {
        this.observe(this@YcBaseActivity, observer)
    }

    fun show(msg: String?) {
        if (this.isFinishing) {
            return
        }
        if (msg == null) {
            Toast.makeText(this, "-", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
        }
    }
}
